Document Object Model (DOM) - tutorial

revision:


Content

The HTML DOM is created by the browser when a web page is loaded. Illustration: HTML DOM animation Finding HTML elements Changing HTML elements Adding and deleting elements Finding HTML objects Manage attributes of elements and/or nodes The HTML DOM allows to execute code when an event occurs. Add event handlers to elements and/or nodes Collections and nodelists 5 major ways of manipulating the DOM some examples JavaScript.info - examples


The HTML DOM is created by the browser when a web page is loaded.

top

The browser creates a Document Object Model (DOM) of the page and the HTML DOM model is constructed as a tree of Objects.

With the object model, JavaScript gets all the power it needs to create dynamic HTML:

it can change all the HTML elements in the page,
it can change all the HTML attributes in the page,
it can change all the CSS styles in the page,
it can remove existing HTML elements and attributes,
it can add new HTML elements and attributes,
it can react to all existing HTML events in the page,
and it can create new HTML events in the page.

The HTML DOM is a standard object model and programming interface for HTML. It defines the HTML elements as objects, the properties of all HTML elements, the methods to access all HTML elements, the events for all HTML elements.

HTML DOM methods are actions that can be performed on HTML elements.

examples

my first page

code:
                  <div class="spec">
                    <p>my first page</p>
                    <a id="demo"></a>
                  </div>
                  <script>
                      document.getElementById("demo").innerHTML = "Hello World!";
                  </script>
              

In the example above, "getElementById" is a method, while "innerHTML" is a property.

The most common way to access an HTML element is to use the "id" of the element. The easiest way to get the content of an element is by using the "innerHTML" property.

P.S.: difference between .innerHTML and .textContent properties: textContent renders text and only text, and innerHTML renders text with any HTML applied to it.

HTML DOM document object is the owner of all other objects in a web page.

The document object represents the web page. If you want to access any element in an HTML page, you always start with accessing the document object.
Below are some examples of how you can use the document object to access and manipulate HTML.

With the HTML DOM, you can navigate the node tree using node relationships.

According to the W3C HTML DOM standard, everything in an HTML document is a node: the entire document is a document node, every HTML element is an element node, the text inside HTML elements are text nodes, every HTML attribute is an attribute node (deprecated), all comments are comment nodes.

With the HTML DOM, all nodes in the node tree can be accessed by JavaScript. New nodes can be created, and all nodes can be modified or deleted.

Node relationships

The nodes in the node tree have a hierarchical relationship to each other. The terms parent, child, and sibling are used to describe the relationships. In a node tree, the top node is called the root (or root node). Every node has exactly one parent, except the root (which has no parent). A node can have a number of children. Siblings (brothers or sisters) are nodes with the same parent.

Navigating between nodes

You can use the following node properties to navigate between nodes with JavaScript: parentNode, childNodes[nodenumber], firstChild, lastChild, nextSibling, previousSibling

Node - instance properties

attributes — returns a live collection of all attributes registered to and element

baseURI — provides the absolute base URL of an HTML element

childNodes — gives a collection of an element's child nodes

firstChild — Returns the first child node of an element

lastChild — The last child node of an element

nextSibling — Gives you the next node at the same node tree level

nodeName — Returns the name of a node

nodeType — Returns the type of a node

nodeValue — Sets or returns the value of a node

ownerDocument — The top-level document object for this node

parentNode — Returns the parent node of an element

previousSibling — Returns the node immediately preceding the current one

textContent — Sets or returns the textual content of a node and its descendants

Node - instance methods

appendChild() — Adds a new child node to an element as the last child node

cloneNode() — Clones an HTML element

compareDocumentPosition() — Compares the document position of two elements

getFeature() — Returns an object which implements the APIs of a specified feature

hasAttributes() — Returns true if an element has any attributes, otherwise false

hasChildNodes() — Returns true if an element has any child nodes, otherwise false

insertBefore() — Inserts a new child node before a specified

isDefaultNamespace() — Returns true if a specified namespaceURI is the default, otherwise false

isEqualNode() — Checks if two elements are equal

isSameNode() — Checks if two elements are the same node

isSupported() — Returns true if a specified feature is supported on the element

lookupNamespaceURI() — Returns the namespaceURI associated with a given node

lookupPrefix() — Returns a DOMString containing the prefix for a given namespaceURI, if present

normalize() — Joins adjacent text nodes and removes empty text nodes in an element

removeChild() — Removes a child node from an element

replaceChild() — Replaces a child node in an element


Illustration: HTML DOM animation

top

Ceate an animation container

All animations should be relative to a container element, which should be created with style = "position: relative". The animation element should be created with style = "position: absolute".

Animation code

JavaScript animations are done by programming gradual changes in an element's style. The changes are called by a timer. When the timer interval is small, the animation looks continuous.

Examples

code:
                <div class="spec">
                  <p><button onclick="myMove()">Click Me</button></p>
                  <div id ="myContainer">
                      <div id ="myAnimation"></div>
                  </div>  
                </div>
                <style>
                    #myContainer {width: 400px; height: 400px; position: relative; background: seagreen; }
                    #myAnimation {width: 50px;  height: 50px; position: absolute; background-color: red;}
                </style>
                <script>
                      function myMove() {
                          let elem = document.getElementById("myAnimation");   
                          let pos = 0;
                          let id = setInterval(frame, 10);
                          function frame() {
                              if (pos == 350) {
                              clearInterval(id);
                              } else {
                                pos++; 
                                elem.style.top = pos + 'px'; 
                                elem.style.left = pos + 'px'; 
                              }
                          }
                      }
                  </script>
              

holiday
code:
                    <div class="spec">
                      <p>
                        <button type="button" onclick="zoomin()"><img src="../pics/zoom-in.png" 
                        width="10"> Zoom In</button>
                        <button type="button" onclick="zoomout()"><img src="../pics/zoom-out.jpg" 
                        width="10"> Zoom Out</button>
                      </p>
                      <img src="../pics/2.jpg" id="holiday" width="250" alt="holiday">
                    </div>
                    <script>
                      function zoomin(){
                          var myImg = document.getElementById("holiday");
                          var currWidth = myImg.clientWidth;
                          if(currWidth == 500){
                              alert("Maximum zoom-in level reached.");
                          } else{
                              myImg.style.width = (currWidth + 50) + "px";
                          } 
                      }
                      function zoomout(){
                          var myImg = document.getElementById("holiday");
                          var currWidth = myImg.clientWidth;
                          if(currWidth == 50){
                              alert("Maximum zoom-out level reached.");
                          } else{
                              myImg.style.width = (currWidth - 50) + "px";
                          }
                      }
                    </script>
              

Tabbed Image Gallery

Click on the images below:

holiday 01
holiday 02
holiday 03
holiday 04
×
code:
                  <div class="spec">
                    <div style="text-align:center">
                        <h4>Tabbed Image Gallery</h4>
                        <p>Click on the images below:</p>
                    </div>
                    <div class="row">
                        <div class="column"><img src="../pics/1.jpg" alt="holiday 01" style="width:100%" onclick="myFunction(this);"></div>
                        <div class="column"><img src="../pics/2.jpg" alt="holiday 02" style="width:100%" onclick="myFunction(this);"></div>
                        <div class="column"><img src="../pics/3.jpg" alt="holiday 03" style="width:100%" onclick="myFunction(this);"></div>
                        <div class="column"><img src="../pics/4.jpg" alt="holiday 04" style="width:100%" onclick="myFunction(this);"></div>
                    </div>
                    <div class="container">
                      <span onclick="this.parentElement.style.display='none'" class="closebtn">×</span>
                      <img id="expandedImg" style="width:50%">
                      <div id="imgtext"></div>
                    </div>
                  </div>
                  <style>
                      .container { position: relative; display: none; }
                      #imgtext { position: absolute;  bottom: 15px; left: 15px; color: white; font-size: 20px;}
                      .closebtn { position: absolute; top: 10px; left: 20px; color: white; font-size: 35px;  cursor: pointer;}
                  </style>
                  <script>
                      function myFunction(imgs) {
                        let expandImg = document.getElementById("expandedImg");
                        let imgText = document.getElementById("imgtext");
                        expandImg.src = imgs.src;
                        imgText.innerHTML = imgs.alt;
                        expandImg.parentElement.style.display = "block";
                      }
                  </script>
            

Finding HTML elements

top

document.getElementById("id") - find an element by element id.

examples

Hello World!

code:
                <div class="spec">
                  <p id="intro">Hello World! </p>
                  <a id="demo2"> </a>     
                </div>
                <script>
                    var myElement = document.getElementById("intro");
                    document.getElementById("demo2").innerHTML = "The text from the intro paragraph is: " + myElement.innerHTML;
                </script>
            

document.getElementsByTagName("name") - find elements by tag name.

examples

The DOM is very useful.

code:
                  <div class="spec" id="main">
                    <p>The DOM is very useful. </p>
                    <a id="demo3"> </a>   
                  </div>
                  <script>
                        var x = document.getElementById("main");
                        var y = x.getElementsByTagName("p");
                        document.getElementById("demo3").innerHTML = 'The first paragraph (index 0) inside "main" is: ' + y[0].innerHTML;
                  </script>
              

Click the button to change the text of the first list item (index 0).

code:
                <div class="spec">
                    <ul>
                      <li>Coffee </li>
                      <li>Tea </li>
                    </ul>
                    <p>Click the button to change the text of the first list item (index 0). </p>
                    <button onclick="changeText()">Try it </button>
                </div>
                <script>
                    function changeText() {
                        var list = document.getElementsByTagName("ul")[0];
                        list.getElementsByTagName("li")[0].innerHTML = "Milk";
                    }
                </script>
            

getElementsByTagNameNS()

returns a live HTMLCollection of elements with a certain tag name belonging to the given namespace.

document.getElementsByClassName("name") - find elements by class name.

examples

How are you doing!

The DOM is very useful.

code:
                <div class="spec">
                  <p>How are you doing! </p>
                  <pclass="intro">The DOM is very useful. </p>
                  <a id="demo4"> </a>
                </div>
                <script>
                    var z = document.getElementsByClassName("intro");
                    document.getElementById("demo4").textContent = 'The first paragraph (index 0) with class="intro": ' + z[0].textContent;
                </script>
            

finding HTML elements by "CSS selectors".

If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method.

examples

Hope you are doing well today!!

The DOM is very very useful.

code:
                  <div class="spec">
                    <p>Hope you are doing well today!! </p>
                    <p class="intro1">The DOM is very very useful. </p>
                    <a id="demo5"> </a>
                  </div>
                  <script>
                      var aa = document.querySelectorAll("p.intro1");
                      document.getElementById("demo5").innerHTML = 'The first paragraph (index 0) with class="intro": ' + aa[0].innerHTML;
                  </script>
              

finding HTML elements by "HTML object collections".

examples

This example finds the form element with id="frm1", in the forms collection, and displays all element values.

First name:

Last name:

Click "Try it" to display the value of each element in the form.


code:
                    <div class="spec">
                      <p>This example finds the form element with id="frm1", in the forms collection,
                        and displays all element values. </p>
                      <form id="frm1" action="/action_page.php">
                          <p>First name:  <input type="text" name="fname" value="Donald"> </p>
                          <p>Last name:  <input type="text" name="lname" value="Duck"> </p>
                          <input type="submit" value="Submit">
                      </form> 
                      <p>Click "Try it" to display the value of each element in the form. </p>
                      <button onclick="myFunctionA()">Try it </button><br>
                      <a id="demo6"> </a>      
                    </div>
                    <script>
                          function myFunctionA() {
                            var x = document.forms["frm1"];
                            var text = "";
                            var i;
                            for (i = 0; i  < x.length ;i++) {
                              text += x.elements[i].value + " , ";
                            }
                            document.getElementById("demo6").innerHTML = text;
                          }
                    </script>
              

Changing HTML elements

top

property: element.innerHTML = "new HTML content" - change the inner HTML of an element.

examples

Hello World!

code:
              <div class="spec">
                <p id="prop1">Hello World! </p>
                <button style="margin-left: 4vw;" onclick="functionChange()">click me </button>
              </div>
              <script>
                  function functionChange(){
                    document.getElementById("prop1").innerHTML = "New text!";
                  }
              </script>    
          

example: JavaScript can change HTML

original text: Hi, there. How are you?
Hi, there. How are you?
code:
                <div class="spec">
                  <p>example: JavaScript can change HTML </p>
                  <a>original text: Hi, there. How are you? </a> <br>
                  <a id="p1">Hi, there. How are you? </a>
                </div>
                <script>
                  document.getElementById("p1").innerHTML = "Never be afraid to try the implossible!";
                </script>
          

example: JavaScript can change HTML

original text: Hi, there. How are you?
Hi, there. How are you?
code:
                <div class="spec">
                  <p>example: JavaScript can change HTML </p>
                  <a>original text: Hi, there. How are you? </a> <br>
                  <a id="p2">Hi, there. How are you? </a>
                </div>
                <script>
                  document.getElementById("p2").innerHTML = "Never be afraid to try the implossible!";
                </script>
          

property: element.attribute = "new value" - change the attribute value of an HTML element.

examples

code:
                <div class="spec">
                  <img  id="prop2" src="../pics/1.jpg" width="160" height="120">
                  <button onclick="functionPicture()">click me </button>
                </div>
                <script>
                    function functionPicture(){
                        document.getElementById("prop2").src = "../pics/2.jpg";
                    }
                </script>
            

To change the value of an HTML attribute, use this syntax: document.getElementById("id").attribute = "new value"

examples

original picture

code:
                    <div class="spec">
                      <p>original picture </p>
                      <img id="image" src="1.jpg" width="160" height="120">
                      <img id="image1" src="1.jpg" width="160" height="120">
                    </div>
                    <script>
                        document.getElementById("image1").src = "2.jpg";
                  </script>
            

property: element.style.property = "new style" - change the style of an HTML element.

examples

Hello World!

code:
                <div class="spec">
                  <p id="prop3">Hello World! </p>
                  <button onclick="colorChange()">click me </button>
                </div>
                <script>
                    function colorChange(){
                          document.getElementById("prop3").style.color = "red";
                    }
                </script>
            

Hope you are doing well!!

Hope you are doing well!!

code:
              <div class="spec">
                <p id="p2">Hope you are doing well!! </p>
                <p id="p3">Hope you are doing well!! </p>
              </div>
              <script>
                  document.getElementById("p3").style.color = "blue";
                  document.getElementById("p3").style.fontFamily = "monospace";
                  document.getElementById("p3").style.fontSize = 25 + "px";
              </script>
          

method: element.setAttribute("attribute", "value") - set or change the attribute value of an HTML element.

examples

Click the button below to change the input field to an input button.

code:
                  <div class="spec">
                    <input style="margin-left: 4vw;" value="OK">
                    <p style="margin-left: 4vw;">Click the button below to change the input 
                    field to an input button. </p>
                    <button style="margin-left: 4vw;" onclick="changeInput()">try it </button>
                </div>
                <script>
                    function changeInput() {
                      document.getElementsByTagName("INPUT")[3].setAttribute("type", "button"); 
                    }
                </script>
            

Adding and deleting elements

top

document.createElement("element") - create an HTML element.

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

examples

Create a p element with some text:

code:
          <div>
            <p>Create a p element with some text:</p>
            <p id="DOM-AA"></p>
          </div>
          <script>
            // Create element:
            const para = document.createElement("p");
            para.innerText = "This is a paragraph.";
            // Append to body:
            document.getElementById("DOM-AA").appendChild(para);
          </script>
        

This is a paragraph.

This is another paragraph.

code:
            <div class="spec">
                <div id="div1">
                    <p id="p1">This is a paragraph.</p>
                    <p id="p2">This is another paragraph.</p>
                </div>
            </div>
            <script>
                  var para = document.createElement("p");
                  var node = document.createTextNode("This is a new paragraph.");
                  para.appendChild(node);
                  var element = document.getElementById("div1");
                  element.appendChild(para);
            </script>
        

Example explained:

This code creates a new "p" element : var para = document.createElement("p");.
To add text to the "p" element, you must create a text node first. This code creates a text node : var node = document.createTextNode("This is a new paragraph.");.
Then you must append the text node to the "p" element : para.appendChild(node);.
Finally you must append the new element to an existing element. This code finds an existing element : var element = document.getElementById("div1");
This code appends the new element to the existing element : element.appendChild(para);

document.element.appendChild("element") - add an HTML element (node) as the last child of an element.

examples

Click "Append" to append an item to the end of the list:

code:
            <div>
              <ul id="myList2">
                <li>Coffee</li>
                <li>Tea</li>
              </ul>
              <p>Click "Append" to append an item to the end of the list:</p>
              <button onclick="appendFunction()">Append</button>
            </div>
          <script>
            function appendFunction() {
                // Create an "li" node:
                const node = document.createElement("li");
                // Create a text node:
                const textnode = document.createTextNode("Water");
                // Append the text node to the "li" node:
                node.appendChild(textnode);
                // Append the "li" node to the list:
                document.getElementById("myList2").appendChild(node);
            }
          </script>
          

element.insertBefore(new, existing) || node.insertBefore(new, existing) - inserts a child node before an existing child.

The appendChild() method appends the new element as the last child of the parent. If you don't want that you can use the insertBefore() method.

Parameters:

new : required. The node (element) to insert.

existing : required. The node (element) to insert before. If null, it will be inserted at the end.

examples

click the button to move an item from one list to another

code:
              <div class="spec">
                <ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
                <ul id="myList2"><li>Water</li><li>Milk</li></ul>
                <p>click the button to move an item from one list to another</p>
                <button onclick="myFunctionZ()">Try it</button>
              </div>
              <script>
                function myFunctionZ() {
                  var node = document.getElementById("myList2").lastChild;
                  var list = document.getElementById("myList1");
                  list.insertBefore(node, list.childNodes[0]);
                }
              </script>
        

element.remove() || node.remove()

Parameters: none;

examples

Click "Remove", and this paragraph will be removed from the DOM.

code:
          <div>
            <p id="remove2">Click "Remove", and this paragraph will be removed from the DOM.</p>
            <button onclick="removeF()">Remove</button>
          </div>
          <script>
            function removeF() {
              const element = document.getElementById("remove2");
              element.remove();
            }
          </script>
        

document.element.removeChild("element") - remove an HTML element's child.

examples

Click "Remove" to remove the first item from the list:

code:
            <div>
              <p>Click "Remove" to remove the first item from the list:</p>
              <button onclick="removeFunction()">Remove</button>
              <ul id="myList">
                <li>Coffee</li>
                <li>Tea</li>
                <li>Milk</li>
              </ul>
              
            </div>
            <script>
              function removeFunction() {
                const list = document.getElementById("myList");
                list.removeChild(list.firstElementChild);
              }
            </script>
          

Click "Remove" to remove to remove all child nodes of ul.

code:
          <div>
            <p>Click "Remove" to remove to remove all child nodes of ul.</p>
            <button onclick="removeFunction1()">Remove</button>
            <ul id="myListB">
              <li>Coffee</li>
              <li>Tea</li>
              <li>Milk</li>
            </ul>
          </div>
          <script>
            function removeFunction1() {
              const listB = document.getElementById("myListB");
              while (listB.hasChildNodes()) {
                listB.removeChild(listB.firstChild);
              }
            }
          </script>
        

document.element.replaceChild(new, old) - replace an HTML element (child node) with a new element (node).

examples

Click "Replace" to replace the first item in the the list.

This example replaces the Text node "Coffee" with a Text node "Water". Replacing the entire li element is also an alternative.

code:
            <div>
              <ul id="myList4">
                <li>Coffee</li>
                <li>Tea</li>
                <li>Milk</li>
              </ul>
              <p>Click "Replace" to replace the first item in the the list.</p>
              <button onclick="replaceFunction()">Replace</button>
              <p>This example replaces the Text node "Coffee" with a Text node "Water". Replacing the entire li element is
              also an alternative.</p>
          </div>
          <script>
            function replaceFunction() {
                // Select first child element:
                const element = document.getElementById("myList4").children[0];
                // Create a new text node:
                const newNode = document.createTextNode("Water");
                // Replace the text node:
                element.replaceChild(newNode, element.childNodes[0]);
                }
          </script>
          

document.write(text) - write into the HTML output stream.


Finding HTML objects

top

document.anchors - returns all "a" elements that have a name attribute.

Deprecated. Do not use it

document.baseURI - returns the absolute base URI of the document.

The baseURI property is read-only and it returns the absolute base URL of the document containing the node.

examples

The base URI of the document is:

code::
              <div>
                <p>The base URI of the document is:</p>
                <p id="find-1"></p>
              </div>
              <script>
                  let base = document.baseURI;
                  document.getElementById("find-1").innerHTML = base;
              </script>
            

document.body - returns the "body" element.

Setting the body property overwrites all elements in the document's <body>.

Set the body property - Syntax : document.body = newContent

Parameters: none

example code:
            <div>
              <p>Display the HTML content of this document:</p>
              <p id="find-2"></p>
            </div>
            <script>
              const myBody = document.body.innerHTML;
              document.getElementById("find-2").innerHTML = myBody;
              document.body.style.backgroundColor = "yellow";
              document.body.innerHTML = "Some new HTML content";
            </script>
          

document.cookie - returns the document's cookie.

The cookie property sets or returns a semicolon-separated list of key=value pairs (document cookies).

set the cookie - Syntax : documnet.cookie = newCookie

Parameters: a semicolon-separated list of name=value pairs, followed with any of these optional values:

expires=date : a date in GMT format (Use the Date.toUTCString method). Default value: The cookie is deleted when the browser is closed.

max-age=seconds : the max age before the cookie is deleted. If to 0 or a date in the past, the cookie is deleted.

path=path : an absoulute path to the directory the cookie belongs to ('/dir'). Default value: Current directory.

domain=domainname : the domain of the site ('example.com').Default value: The domain of the document.

secure : Use a secure protocol (https) for sending the cookie to the server.

examples

Cookies associated with this document:

code:
            <div>
              <p>Cookies associated with this document:</p>
              <p id="find-3"></p>
            </div>
            <script>
              let allCookies = document.cookie;
              document.getElementById("find-3").innerHTML = allCookies;
            </script>
          

document.doctype - returns the document's doctype.

The doctype property returns null if the document has no doctype. The doctype property is read-only. The doctype.name property returns the name of the doctype.

Parameters: none

examples

The document.doctype.name is:

code::
            <div>
              <p>The document.doctype.name is:</p>
              <p id="find-4"></p>
            </div>
            <script>
              const doctypeObj = document.doctype;
              document.getElementById("find-4").innerHTML = doctypeObj.name;
            </script>
          

document.documentElement - returns the "html" element.

The documentElement property returns a document's element (as an Element object). The documentElement is read-only. For HTML documents the returned object is the <html> element.

Parameters: none

examples

The element node is:

code::
            <div>
              <p>The element node is:</p>
              <p id="find-5"></p>
            </div>
            <script>
              document.getElementById("find-5").innerHTML = document.documentElement.nodeName;
            </script>
          

document.documentMode - returns the mode used by the browser.

The documentMode property is deprecated. Do NOT use it.

document.documentURI - returns the URI of the document.

The documentURI property returns null if the document was created in memory.

set the documentURI property - Syntax: document.documentURI = locationURI

Parameters: none

examples

The location of this document is:

code::
            <div>
              <p>The location of this document is:</p>
              <p id="find-6"></p>
            </div>
            <script>
                let uri = document.documentURI;
                document.getElementById("find-6").innerHTML = uri;
            </script>
          

document.domain - returns the domain name of the document server.

The domain property returns null if the document was created in memory.

Parameters: none

examples

The domain name of the server this document was loaded from:

code:
            <div>
              <p>The domain name of the server this document was loaded from:</p>
              <p id="find-7"></p>
            </div>
            <script>
                let myDomain = document.domain;
                document.getElementById("find-7").innerHTML = myDomain;
            </script>
          

document.embeds - returns all "embed" elements.

The embeds property returns a collection of all <embed> elements in the document. The embeds property is read-only.

Parameters: none

Properties :

length : The number of <embed> elements in the collection.

Methods:

[index] : returns the element with the specified index (starts at 0). Returns null if the index is out of range.

item(index) : returns the element with the specified index (starts at 0). Returns null if the index is out of range.

namedItem(id) : returns the element with the specified id. Returns null if the id does not exist.

examples

The number of embed elements in this document:

code:
            <div>
              <p>The number of embed elements in this document:</p>
              <p id="find-8"></p>
              <embed type="image/jpg" src="1.jpg" width="50%" height="30%">
              <embed type="image/jpg" src="2.jpg"  width="50%" height="30%">
            </div>
            <script>
              let num = document.embeds.length;
              document.getElementById("find-8").innerHTML = num;
            </script>
          

document.forms - returns all "form" elements.

The forms property returns a collection of all <form> elements in a document. The forms property returns an HTMLCollection. The forms property is read-only.

Parameters: none

Properties :

length : The number of elements in the collection.

Methods:

[index] : returns the element with the specified index (starts at 0). Returns null if the index is out of range.

item(index) : returns the element with the specified index (starts at 0). Returns null if the index is out of range.

namedItem(id) : returns the element with the specified id. Returns null if the id does not exist.

examples

First Name:

Last Name:

The number of form elements in the document is:

code::
            <div>
              <form>
                <p>First Name: <input type="text" name="fname" value="Donald"></p>
                <p>Last Name: <input type="text" name="lname" value="Duck"></p>
              </form>
              <p>The number of form elements in the document is:</p>
              <p id="find-9"></p>
            </div>
            <script>
                let num1 = document.forms.length;
                document.getElementById("find-9").innerHTML = num1;
            </script>
          

document.head - returns the "head" element.

Parameters: none

examples

The tag name of the head property is:

code:
            <div>
              <p>The tag name of the head property is:</p>
              <p id="find-10"></p>
            </div>
            <script>
                let tag = document.head.tagName;
                document.getElementById("find-10").innerHTML = tag;
            </script>
          

document.images - returns all "img" elements.

The images property returns a collection of all <img> elements in a document. The images property returns an HTMLCollection. The images property is read-only.

Parameters: none

Properties :

length : The number of <img> elements in the collection.

Methods:

[index] : returns the element with the specified index (starts at 0). Returns null if the index is out of range.

item(index) : returns the element with the specified index (starts at 0). Returns null if the index is out of range.

namedItem(id) : returns the element with the specified id. Returns null if the id does not exist.

examples

The number of images is:

code:
            <div>
              <p>The number of images is:</p>
              <p id="find-12"></p>
            </div>
            <script>
              let numb = document.images.length;
              document.getElementById("find-12").innerHTML = numb;
      
            </script>
          

document.implementation - returns the DOM implementation.

The implementation property returns the DOMimplementation object that handles the document.

Parameters: none

examples

Does this document has the feature DOM 1.0?

code:
            <div>
              <p>Does this document has the feature DOM 1.0?</p>
              <p id="find-13"></p>
            </div>
            <script>
                let answer2 = document.implementation.hasFeature("DOM", "1.0");
                document.getElementById("find-13").innerHTML = answer2;
            </script>
          

document.inputEncoding - returns the document's encoding (character set).

The inputEncoding property is deprecated. Do NOT use it.

document.lastModified - returns the date and time the document was updated.

The lastModified property returns the date and time the document was last modified. The lastModified property is read-only.

Parameters: none

examples

This document was last modified:

code::
            <div>
              <p>This document was last modified:</p>
              <p id="find-14"></p>
            </div>
            <script>
              let text = document.lastModified;
              document.getElementById("find-14").innerHTML = text;
            </script>
          

document.links - returns all "area" and "a" elements that have a href attribute.

The links property returns a collection of all links in the document. The links property returns an HTMLCollection. The links property is read only. The links in the collection represents <a> and <area> elements with an href attribute.

Parameters: none

Properties :

length : The number of elements in the collection.

Methods:

[index] : returns the element with the specified index (starts at 0). Returns null if the index is out of range.

item(index) : returns the element with the specified index (starts at 0). Returns null if the index is out of range.

namedItem(id) : returns the element with the specified id. Returns null if the id does not exist.

examples

my website

my other website

The number of links in the document is:

code:
            <div>
              <p><a href="www.lwitters.com">my website</a></p>
              <p><a href="www.lwitters-1.com">my other website</a></p>
      
              <p>The number of links in the document is:</p>
              <p id="find-15"></p>
            </div>
            <script>
              let numb2 = document.links.length;
              document.getElementById("find-15").innerHTML = numb2;
            </script>
          

document.readyState - returns the (loading) status of the document.

The readyState property returns the (loading) status of the current document.The readyState property is read-only.

Parameters: none

examples

code:
            <div>
              <p id="find-16"></p>
            </div>
            <script>
              document.getElementById("find-16").innerHTML = document.readyState;;
            </script>
          

document.referrer - returns the URI of the referrer (the linking document).

The referrer property returns the URL of the document that loaded the current document. The referrer property is read-only.

Parameters: none

examples

code:
            <div>
              <p id="find-17"></p>
            </div>
            <script>
              document.getElementById("find-17").innerHTML = document.referrer;
            </script>
          

document.scripts - returns all "script" elements.

The scripts property returns a collection of all <script> elements in the document. The scripts property returns an HTMLCollection. The scripts property is read-only.

Parameters: none

Properties :

length : The number of elements in the collection.

Methods:

[index] : returns the element with the specified index (starts at 0). Returns null if the index is out of range.

item(index) : returns the element with the specified index (starts at 0). Returns null if the index is out of range.

namedItem(id) : returns the element with the specified id. Returns null if the id does not exist.

examples

The number of script elements in the document:

code:
            <div>
              <p>The number of script elements in the document:</p>
              <p id="find-18"></p>
            </div>
            <script>
              document.getElementById("find-18").innerHTML = document.scripts.length;
            </script>
          

document.strictErrorChecking- returns if error checking is enforced.

The strictErrorChecking property is deprecated. Do NOT use it.

document.title - returns the "title" element.

set the title property - Syntax : documwnt.title = newTitle

Properties :

newTitle : The new document title.

Parameters: none

examples

The title of this document is:

code:
            <div>
              <p>The title of this document is:</p>
              <p id="find-19"></p>
            </div>
            <script>
              document.getElementById("find-19").innerHTML = document.title;
            </script>
          

document.URL - returns the complete URL of the document.

Parameters: none

examples

code:
            <div>
              <p id="find-20"></p>
            </div>
            <script>
                let url = document.URL;
                document.getElementById("find-20").innerHTML = url;
            </script>
          

Manage attributes of elements and/or nodes

top

element.getAttribute('name') — returns the specified attribute value of an element (node).

Parameters:

name : required. The name of the attribute.

examples

Hello World

Click the button to display the value of the class attribute of the h5 element.

code:
                  <div class="spec">
                    <h5 class="democlass">Hello World </h5>
                    <p>Click the button to display the value of the class attribute of the h5 element. </p>
                    <button onclick="getMe()">Try it </button>
                    <p id="get01"> </p>
                  </div>
                  <script>
                      function getMe() {
                        var x = document.getElementsByTagName("h5")[0].getAttribute("class"); 
                        document.getElementById("get01").innerHTML = x;
                      }
                  </script>
            

elementNode.getAttributeNS(ns, name) — returns string value of the attribute with the specified namespace URI and name.

XML DOM

Parameters:

ns : required. Specifies the namespace URI to get the attribute value from

name : required. Specifies the attribute to get the attribute value from

element.getAttributeNode('name') — gets the specified attribute node and returns an attribute object.

Parameters:

name : required. The name of the attribute.

examples

Click the button to display the value of the onclick attribute node of the button element.

code:
                  <div class="spec">
                    <p>Click the button to display the value of the onclick attribute node 
                    of the button element. </p>
                    <button id="myButton" onclick="getIt()">Try it </button>
                    <p id="get2"> </p>
                  </div>
                  <script>
                      function getIt() {
                        var element = document.getElementById("myButton");
                        var attr = element.getAttributeNode("onclick").value;
                        document.getElementById("get2").innerHTML = attr;
                      }
                  </script>
              

elementNode.getAttributeNodeNS(ns, name) — returns the attribute node for the attribute with the given namespace and name.

XML DOM

Parameters:

ns : required. Specifies the namespace URI to get the attribute value from

name : required. pecifies the attribute to get the attribute value from

element.setAttribute('name', 'value') — sets a new value to an attribute. If the attribute does not exist, it is created first.

Parameters:

name : required. The name of the attribute.

value : required. The new attribute value.

examples

The Element Object

Click "Add Class" to add a class attribute to the h1 element:

code: <pre> <div> <h4 id="myH4">The Element Object</h4> <p>Click "Add Class" to add a class attribute to the h1 element:</p> <button onclick="setFunction()">Add Class</button> </div> <style> .democlass {color: red;} </style> <script> function setFunction() { document.getElementById("myH4").setAttribute("class", "democlass"); } </script> </pre>

elementNode.setAttributeNS(ns, name, value) — adds a new attribute or changes the value of an attribute with the given namespace and name.

XML DOM

Parameters:

ns : required. Specifies the namespace URI of the attribute to set

name : required. Specifies the name of the attribute to set

value : required. Specifies the value of the attribute to set

element.setAttributeNode(node) — sets or changes the specified attribute node and returns an attribute object.

The setAttribute() method replaces attribute values. The setAttributeNode() method replaces Attribute objects.

Parameters:

node : required. The attribute node to add.

examples

A Link: Go to my Website

Click the button to create a "class" attribute with the value "www.lwitters.com" and insert it to the <a> element above.

code:
                  <div class="spec">
                    <a id="myAnchor_b">A Link: Go to my Website </a>
                    <p>Click the button to create a "class" attribute with the value 
                    "www.lwitters.com" and insert it to the <a> element above. </p>
                    <button onclick="myF()">Try it </button>
                  </div>
                  <script>
                      function myF() {
                        var anchor = document.getElementById("myAnchor_b");
                        var att = document.createAttribute("href");
                        att.value = "https://www.lwitters.com";
                        anchor.setAttributeNode(att);
                      }
                  </script>
            

elementNode.setAttributeNodeNS(att_node) — adds a new namespaced attribute node to an element.

XML DOM

Parameters:

att_node : required. Specifies the attribute node to set

element.hasAttribute('name') — returns true if an element has any attributes, otherwise false.

Parameters:

name : required. The name of the attribute

examples

Click the button to find out if the button element has an onclick attribute.

code:
                   <div class="spec">
                     <p>Click the button to find out if the button element has an onclick attribute. </p>
                     <button id="my_Btn" onclick="getAttr()">Try it </button>
                     <p id="get3"> </p>
                   </div>
                   <script>
                      function getAttr() {
                        var X = document.getElementById("my_Btn").hasAttribute("onclick");
                        document.getElementById("get3").innerHTML = X;
                      }
                   </script>
              

element.hasAttributes() || node.hasAttributes() — returns true if an element has attributes, otherwise false.

Parameters: none

examples

The body element has attributes:

code:
                    <div class="spec">
                      <p>The body element has attributes:</p>
                      <p id="attr1"></p>
                    </div>
                    <script>
                        let answer = document.body.hasAttributes();
                        document.getElementById("attr1").innerHTML = answer;
                    </script>
                

elementNode.hasAttributeNS(ns, name) — provides a true/false value indicating whether the current element in a given namespace has the specified attribute.

XML DOM

Parameters:

ns : required. Specifies the namespace of the attribute to find

name : required. Specifies the name of the attribute to find

element.removeAttribute('name') — removes a specified attribute from an element

examples

a Link: Go to my website

Click the button to remove the href attribute from the a element.

code:
                  <div class="spec">
                    <a id="myAnchor" href="https://lwitters.com">a Link: Go to my website </a>
                    <p id="get4">Click the button to remove the href attribute from the a element. </p>
                    <button onclick="removeAttr()">Try it </button>
                  </div>
                  <script>
                    function removeAttr() {
                      document.getElementById("myAnchor").removeAttribute("href"); 
                    }
                  </script>
            

elementNode.removeAttributeNS(ns, name) — removes the specified attribute from an element within a certain namespace.

XML DOM

Parameters:

ns : required. Specifies the namespace of the attribute to remove

name : required. Specifies the name of the attribute to remove

element.removeAttributeNode(node) — takes away a specified attribute node and returns an attribute object

Parameters:

node : required. The attribute node to remove.

examples

A Link: Go to My Website

Click the button to remove the href attribute node from the a element.

code:
                    <div class="spec">
                      <a id="myAnchor_a" href="https://www.lwitters.com">A Link: Go to My Website </a>
                      <p id="get5">Click the button to remove the href attribute node from the a element. </p>
                      <button onclick="removeA()">Try it </button>
                    </div>
                    <script>
                    function removeA() {
                      var elmnt = document.getElementById("myAnchor_a");
                      var attr = elmnt.getAttributeNode("href");
                      elmnt.removeAttributeNode(attr);
                    }
                    </script>
              

The HTML DOM allows to execute code when an event occurs.

top

Events are generated by the browser when "things happen" to HTML elements : an element is clicked on, the page has loaded, input fields are changed, etc.

examples

My Heading 1

code:
                  <div  class="spec">
                    <h4 id="id1">My Heading 1 </h4>
                    <button type="button" onclick="document.getElementById('id1').style.color = 'red'">Click me! </button>
                    <button type="button" onclick="document.getElementById('id1').style.color = 'black'"> Click me also! </button>
                  </div>
                  <script> </script>
            

Reacting to events: a JavaScript function can be executed when an event occurs.

To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute: onclick=JavaScript.

Examples of HTML events:

when a user clicks the mouse;
when a web page has loaded;
when an image has been loaded;
when the mouse moves over an element;
when an input field is changed;
when an HTML form is submitted;
when a user strikes a key.

examples

Click on this text!

code:
                  <div class="spec">
                    <h4 onclick="this.innerHTML='Ooops!'">Click on this text!</h4>  
                  </div>
                  <script></script>
              

Assign events to HTML elements using event attributes

examples

Click the button to display the date.


code:
                  <div class="spec">
                    <p>Click the button to display the date.</p>
                    <button onclick="displayDate()">The time is?</button><br>
                    <a id="p10"></a>  
                  </div>
                  <script>
                      function displayDate() {
                          document.getElementById("p10").innerHTML = Date();
                      }
                  </script>
            

Assign events to HTML elements using JavaScript.

examples

Click "Try it" to execute the displayDate() function.


code:
                  <div class="spec">
                    <p>Click "Try it" to execute the displayDate() function.</p>
                    <button id="myBtn_c">Try it</button><br>  
                    <a id="p11"></a>
                  </div>
                  <script>
                      document.getElementById("myBtn_c").onclick = displayDateA;
                      function displayDateA() {
                        document.getElementById("p11").innerHTML = Date();
                      }
                  </script>
            

The onload and onunload events events are triggered when the user enters or leaves the page.

The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.

The onchange event is often used in combination with validation of input fields.

Below is an example of how to use the onchange. The upperCase() function will be called when a user changes the content of an input field.

examples

Enter your name:

When you leave the input field, a function is triggered which transforms the input text to upper case.

code:
                  <div class="spec">
                    <p>Enter your name: <input type="text" id="fname" onchange="myFunctionC()"></p>
                    <p>When you leave the input field, a function is triggered which transforms
                      the input text to upper case.</p>
                  </div>
                  <script>
                        function myFunctionC() {
                          var x = document.getElementById("fname");
                          x.value = x.value.toUpperCase();
                        }
                  </script> 
            

The onmouseover and onmouseout events can be used to trigger a function when the user mouses over or out of an HTML element.

examples

Mouse Over Me
code:
              <div class="spec">
                <div onmouseover="mOver(this)" onmouseout="mOut(this)">Mouse Over Me</div>
              </div>
              <script>
                    function mOver(obj) {
                        obj.innerHTML = "Thank You"
                    }
                    function mOut(obj) {
                        obj.innerHTML = "Mouse Over Me"
                    }
                </script>
            

The onmousedown, onmouseup, and onclick events are all parts of a mouse-click.

When a mouse-button is clicked, the onmousedown event is triggered. When the mouse-button is released, the onmouseup event is triggered. When the mouse-click is completed, the onclick event is triggered.

examples

Click Me
code:
                    <div class="spec">
                      <div onmousedown="mDown(this)" onmouseup="mUp(this)" 
                      style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
                      Click Me</div>
                    </div>
                    <script>
                      function mDown(obj) {
                          obj.style.backgroundColor = "#1ec5e5";
                          obj.innerHTML = "Release Me";
                        }
                      function mUp(obj) {
                          obj.style.backgroundColor="#D94A38";
                          obj.innerHTML="Thank You";
                        }
                    </script>
              

Add event handlers to elements and/or nodes

top

The addEventListener() method attaches an event handler to the specified element.

This method attaches an event handler to an element without overwriting existing event handlers.
Many event handlers of the same type can be added to one element, i.e two "click" events.
Event listeners can be added to any DOM object and not only HTML elements. i.e. the window object.

The addEventListener() method makes it easier to control how the event reacts to bubbling.
When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.
An event listener can be easily removed by using the removeEventListener() method.

Syntax: element.addEventListener(event, function, useCapture);

Parameters:

event : required. The name of the event. Do not use the "on" prefix. Use "click" not "onclick".

function : required. The function to run when the event occurs.

useCapture : optional (default = false). false - The handler is executed in the bubbling phase. true - The handler is executed in the capturing phase.

Add an event handler to an element.

examples

code:
                  <div class="spec">
                      <button id="myBtn1">Try it</button>
                  </div>
                  <script>
                    document.getElementById("myBtn1").addEventListener("click", function() {
                        alert("How are you doing?");
                    });
                  </script>
              

execute a function when a user clicks on a button.

code:
                    <div class="spec">
                      <button style="margin-left: 4vw;" id="myBtn2">Try it</button>
                    </div>
                    <script>
                          document.getElementById("myBtn2").addEventListener("click", myFunction9);
                          function myFunction9() {
                              alert ("How are you doing today?");
                          }
                    </script>
              

Add many event handlers to the same element

The addEventListener() method allows you to add many events to the same element, without overwriting existing events.

examples

to add two click events to the same button.

code:
                  <div class="spec">
                    <button id="myBtn3">Try it</button>
                  </div>
                  <script>
                        var x = document.getElementById("myBtn3");
                        x.addEventListener("click", myFunction10);
                        x.addEventListener("click", someOtherFunction);
          
                        function myFunction10() {
                          alert ("Hi, there!");
                        }
                        function someOtherFunction() {
                          alert ("some other function was also executed!");
                        }
                  </script>
            

Add an event handler to the window object

The addEventListener() method allows to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.

examples

use the addEventListener() method on the window object.

Try resizing this browser window to trigger the "resize" event handler.

code:
                    <div class="spec">
                      <p>Try resizing this browser window to trigger the "resize" event handler.</p>
                      <a id="event1"></a>
                    </div>
                    <script>
                        window.addEventListener("resize", function(){
                            document.getElementById("event1").innerHTML = Math.random() * 10;
                          });
                    </script>
              

document.getElementById(id).onclick = function(){code} - adding event handler code to an onclick event.

examples

click the button to chang my color.

code:
                  <div class="spec">
                    <p id="a1">click the button to chang my color.</p>
                  <button id="btn1" onclick="changeF()">click</button>
                  </div>
                  <script>
                      function changeF(){
                        document.getElementById('a1').style.color = "red"
                      }
                  </script> 
              

There are two ways of event propagation in the HTML DOM, bubbling and capturing.

Event propagation is a way of defining the element order when an event occurs. If you have a "p" element inside a "div" element, and the user clicks on the "p" element, which element's "click" event should be handled first?

In bubbling, the inner most element's event is handled first and then the outer: the "p" element's click event is handled first, then the "div" element's click event.
In capturing, the outer most element's event is handled first and then the inner: the "div" element's click event will be handled first, then the p" element's click event.

With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter : addEventListener(event, function, useCapture). The default value is false, which will use the bubbling propagation. When the value is set to true, the event uses the capturing propagation.

The removeEventListener() method removes event handlers that have been attached with the addEventListener() method.

Syntax : element.removeEventListener(event, function, capture)

Parameters:

event : required. The name of the event. Do not use the "on" prefix. Use "click" not "onclick".

function : required. The function to remove.

useCapture : optional (default = false). false - The handler is executed in the bubbling phase. true - The handler is executed in the capturing phase.

If the event handler was attached two times, one with capturing and one with bubbling, each must be removed separately.

examples

This orange element has an onmousemove event handler that displays a random number when you move the mouse inside.

Click "Remove" to remove the event handler.

code:
              <div class="spec">
                <div id="myDIV">This orange element has an onmousemove event handler that displays a random number when 
                you move the mouse inside.
                  <p>Click "Remove" to remove the event handler.</p>
                  <button onclick="removeHandler()">Remove</button>
                </div>
                <p id="remove1"></p>
              </div>
              <style>
                #myDIV {background-color: coral; padding: 1vw;}
              </style>
              <script>
                  const myDiv = document.getElementById("myDIV");
                  myDiv.addEventListener("mousemove", removeFunction);
        
                  function removeHandler() {
                    myDiv.removeEventListener("mousemove", removeFunction);
                  }
                  function removeFunction() {
                    document.getElementById("remove1").innerHTML = Math.random();
                  }
              </script>
            

Collections and nodelists

top

HTMLCollection Object

The HTMLCollection interface represents a generic collection (array-like object similar to arguments) of elements (in document order) and offers methods and properties for selecting from the list.

An HTMLCollection in the HTML DOM is live; it is automatically updated when the underlying document is changed. For this reason it is a good idea to make a copy (e.g., using Array.from) to iterate over if adding, moving, or removing nodes.

Instance properties:

The length property defines the number of elements in an HTMLCollection.

Syntax: HTMLCollection.length

instance methods:

HTMLCollection.item() : returns the specific node at the given zero-based index into the list. Returns null if the index is out of range. An alternative to accessing collection[i] (which instead returns undefined when i is out-of-bounds). This is mostly useful for non-JavaScript DOM implementations.
Syntax: HTMLCollection.item(index) || HTMLCollection[index]

HTMLCollection.namedItem() : returns the specific node whose ID or, as a fallback, name matches the string specified by name. Matching by name is only done as a last resort, only in HTML, and only if the referenced element supports the name attribute. Returns null if no node exists by the given name. An alternative to accessing collection[name] (which instead returns undefined when name does not exist). This is mostly useful for non-JavaScript DOM implementations.
Syntax: HTMLCoillection.namedItem(name) || HTMLCollection[name]

The getElementsByTagName() method returns an HTMLCollection object. An HTMLCollection object is an array-like list (collection) of HTML elements.

examples

HTML DOM - collection

The following code selects all "p" elements in a document: var x = document.getElementsByTagName("p"); the elements in the collection can be accessed by an index number. To access the second "p" element you can write:y = x[1];.

Hello World!

Hello Norway!

code:
                <div class="spec">
                  <p>Hello World!</p>
                  <p>Hello Norway!</p>
                  <a id="collection1"></a>  
                  <p></p> 
              </div>
              <script>
                var myCollection = document.getElementsByTagName("p");
                document.getElementById("collection1").innerHTML = "The innerHTML of the second paragraph is: " + myCollection[205].innerHTML;
              </script>
            

An HTMLCollection is NOT an array!

An HTMLCollection may look like an array, but it is not. You can loop through the list and refer to the elements with a number (just like an array). However, you cannot use array methods like valueOf(), pop(), push(), or join() on an HTMLCollection.

HTML DOM nodeList object

The HTML DOM nodelist object is a list (collection) of nodes extracted from a document.
A NodeList object is almost the same as an HTMLCollection object.
Some (older) browsers return a NodeList object instead of an HTMLCollection for methods like getElementsByClassName().
All browsers return a NodeList object for the property childNodes.
Most browsers return a NodeList object for the method querySelectorAll().

examples

The following code selects all "p" nodes in a document: var myNodeList = document.querySelectorAll("p");. The elements in the NodeList can be accessed by an index number.

Hello World!

Hello Norway!

code:
                    <div class="spec">
                        <p>Hello World!</p>
                        <p>Hello Norway!</p>
                        <a id="n1"></a>
                    </div>
                    <script>
                        var myNodelist = document.querySelectorAll("p");
                        document.getElementById("n1").innerHTML = 
                        "The innerHTML of the second paragraph is: " +  myNodelist[214].innerHTML;
                    </script>
              

Properties of a nodelist:

length returns the number of nodes in a NodeList

The length property defines the number of nodes in a node list

examples

Hello World!

Hello Norway!

code:
                  <div class="spec">
                    <p>Hello World!</p>
                    <p>Hello Norway!</p>
                    <a id="n2"></a>
                  </div>
                  <script>
                      var myNodelist1 = document.querySelectorAll("p");
                      document.getElementById("n2").innerHTML = "This document contains " +  myNodelist1.length + " paragraphs.";
                  </script>
              

Methods of a nodelist:

entries() : Returns an Iterator with the key/value pairs from the list

forEach() : Executes a callback function for each node in the list

item() : Returns the node at a specified index

keys() : Returns an Iterator with the keys from the list

values() : Returns an Iterator with the values from the list

examples

Hello World!

Hello Norway!

Click the button to change the color of all p elements in this example.

code:
                <div class="spec">
                  <p class="node1">Hello World!</p>
                  <p class="node1">Hello Norway!</p>
                  <p>Click the button to change the color of all p elements in this example.</p>
                  <button onclick="myFunctionX()">Try it</button>
                </div>
                <script>
                    function myFunctionX() {
                        var myNodelist2 = document.querySelectorAll(".node1");
                        var i;
                        for (i = 0; i < myNodelist2.length; i++) {
                          myNodelist2[i].style.color = "red";
                        }
                    }
                </script>
              

The difference between an HTMLCollection and a NodeList.

An HTMLCollection is a collection of HTML elements. A NodeList is a collection of document nodes. A NodeList and an HTML collection is very much the same thing.
Both an HTMLCollection object and a NodeList object is an array-like list (collection) of objects.
Both have a length property defining the number of items in the list (collection).
Both provide an index (0, 1, 2, 3, 4, ...) to access each item like an array. HTMLCollection items can be accessed by their name, id, or index number. NodeList items can only be accessed by their index number.
Only the NodeList object can contain attribute nodes and text nodes.

A node list is not an array! A node list may look like an array, but it is not. You can loop through the node list and refer to its nodes like an array. However, you cannot use Array Methods, like valueOf(), push(), pop(), or join() on a node list.


5 major ways of manipulating the DOM

top

1/ getElementById() method

The most common way to access an HTML element is to use the id of the element, which is case-sensitive. Once an element is selected, styles can be added to the element, its attributes can be manuipulated, and it can be traversed to parent and child elements.

examples

change the color of this text!
code:
                    <div class="spec">
                      <a id="DOM01">change the color of this text!</a><br>  
                      <button onclick="changeColor('magenta');">magenta</button>
                      <button onclick="changeColor('red');">red</button>
                    </div>
                    <script>
                      function changeColor(newColor) {
                            let elem = document.getElementById('DOM01');
                            elem.style.color = newColor;
                      }
                    </script>
              


code:
                    <div class="spec">
                      <input type="text" id="DOM02" name="number/"><br>  
                      <input type="button" value="cube" onclick="getCube()"/><br> 
                      <a style="color:red" id="DOM03"></a>  
                    </div>
                    <script>
                        function getCube(){
                            let number = document.getElementById("DOM02").value;
                            document.getElementById("DOM03").innerHTML = number*number*number; 
                        }
                    </script>
              

2/ getElementsByClassName() method

This method returns a collection of all elements in the document with the specified class name.

examples

i love javascript

i love react

i want a job
code:
                  <div class="spec">
                    <p class="master2">i love javascript</p>
                    <p class="master2">i love react</p>
                    <h5 class="master2">i want a job</h5>
                    <button id="btn">click me</button>       
                  </div>
                  <script>
                        const btn = document.getElementById('btn');
                        btn.addEventListener('click', function master(){
                            var master = document.getElementsByClassName("master2");
                            master[2].innerHTML = 'i need a job';
                        })
                  </script>
              

3/ getElementsByTagName() method

This method accepts a tag name and returns all the elements of the specified tag name in the order in which they appear in the document.

examples

JavaScript getElementsByTagName() Demo

First heading

This is the first paragraph.

Second heading

This is the second paragraph.

Third heading

This is the third paragraph.



code:
                <div class="spec">
                  <h4>JavaScript getElementsByTagName() Demo</h4>
                  <h5 class="h5">First heading</h5>
                  <p class="para">This is the first paragraph.</p>
                  <h5 class="h5">Second heading</h5>
                  <p class="para">This is the second paragraph.</p>
                  <h5 class="h5">Third heading</h5>
                  <p class="para">This is the third paragraph.</p>      
                  <button id="btnCount">Count h5</button><br>
                  <a style="color:red" id="DOM04"></a> <br>
                  <a style="color:blue" id="DOM05"></a> 
                </div>
                <script>
                  let btn_B = document.getElementById('btnCount');
                  btn_B.addEventListener('click', () => {
                      let headings = document.getElementsByTagName('h5');
                      document.getElementById("DOM04").innerHTML = `number of h5 tags: ${headings.length}`;
                      let para = document.getElementsByClassName("para");
                      document.getElementById("DOM05").innerHTML = "number of p tags: " + para.length;
                  });
                </script>
            

4/ element.querySelector()

This method returns the first value that matches the selector. This method can accept all CSS style selectors, allowing it to select by tag, class, or ID. The method takes one argument, which is a CSS selector, and returns the first element that matches the selector.

examples

A heading with class="DOM05"

A paragraph with class="DOM05".

click the button to add a background color to the first element in the document with class="DOM05".

code:
                    <div class="spec">
                      <h4 class="DOM05">A heading with class="DOM05"</h2>
                      <p class="DOM05">A paragraph with class="DOM05".</p> 
                      <p>click the button to add a background color to the first element in 
                      the document with class="DOM05".</p>
                      <button onclick="changeFunction()">try it</button>        
                    </div>
                    <script>
                        function changeFunction() {
                            document.querySelector(".DOM05").style.backgroundColor = "red";               
                        }
                  </script>
              

5/ element.querySelectorAll()

This method returns a node list collection of all matching elements.

examples

A heading with class="DOM06"

A paragraph with class="DOM06".

Another paragraph with class="DOM06".

click the button to add a background color to all the elements in the document with class="DOM06".

code:
                  <div class="spec">
                    <h4 class="DOM06">A heading with class="DOM06"</h2>
                    <p class="DOM06">A paragraph with class="DOM06".</p> 
                    <p class="DOM06">Another paragraph with class="DOM06".</p> 
                    <p>click the button to add a background color to the first element in 
                    the document with class="DOM06".</p>
                    <button onclick="changeAll()">try it</button>     
                  </div>
                  <script>
                      function changeAll() {
                          let x, i;
                          x = document.querySelectorAll(".DOM06");
                          for (i = 0; i < x.length; i++) {
                              x[i].style.backgroundColor = "red";
                          }
                      }
                  </script>
            

Post Scriptum

If we already have a reference to a parent element, we can just query that element's children instead of the whole document. Having narrowed down the context like this, we can simplify selectors and increase performance. E.g. const myChildElement = myElement.querySelector('input[type="submit"]')

The result of .querySelector() is not live. When we dynamically add an element that matches a selector, the collection won't update. Another consideration is that such a live collection doesn't need to have all of the information up front, whereas .querySelectorAll() immediately gathers everything in a static list, making it less performant.


some examples

top
examples

Kid's allowance

code:
          <div class="spec">
            <label for="shopping-check">Has the shopping been done? </label>
            <input type="checkbox" id="shopping-check">
            <h5 id="allowance"></h5>
          </div>
          <script>
                const checkBox = document.querySelector('#shopping-check');
                const para1a = document.querySelector('#allowance');
                let shoppingDone = false;
          
                checkBox.addEventListener('change',function() {
                  checkBox.disabled = true;
                  shoppingDone = true;
                  updateAllowance();
                });
          
                function updateAllowance() {
                  if(shoppingDone === true) {
                    var childsAllowance = 10;
                  } else {
                    var childsAllowance = 5;
                  }
                  para1a.textContent = 'Child has earned $' + childsAllowance + ' this week.';
                }
                updateAllowance();
          </script>
        


code:
              <div class="spec">
                <label for="weather">Select the weather type today: </label><br>
                <select class="spec"  id="weather">
                    <option value="">--Make a choice--</option>
                    <option value="sunny">Sunny</option>
                    <option value="rainy">Rainy</option>
                    <option value="snowing">Snowing</option>
                    <option value="overcast">Overcast</option>
                </select><br>
                <a id="temp"></a>   
              </div>
              <script>
                  const select = document.querySelector('select');
                  const paraf = document.querySelector('#temp');
                  let temperature = 29;
                  select.onchange = setWeather;
      
                  function setWeather() {
                      const choice = select.value;
      
                      if(choice === 'sunny') {
                      paraf.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.';
                      } else if(choice === 'rainy') {
                      paraf.textContent = 'Rain is falling outside; take a rain coat and a brolly, and don\'t stay out for too long.';
                      } else if(choice === 'snowing') {
                      paraf.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.';
                      } else if(choice === 'overcast') {
                      paraf.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.';
                      } else {
                      paraf.textContent = '';
                      }
                  }
              </script>  
        

My cats

code:
            <div class="spec">
              <a id="cat"></a>
            </div>
            <script>
                const cats = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin'];
                let info = 'My cats are called: ';
                const parag = document.querySelector('#cat');
    
                for(let i = 0; i < cats.length; i++) {
                info += cats[i] 
                + ', ';
                }
                parag.textContent = info;
            </script>
        
code:
        <div class="spec">
          <a id="cat1"></a>    
        </div>
        <script>
            const cats1 = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin'];
            let info1 = 'My cats are called as follows: ';
            const paragr = document.querySelector('#cat1');

            for(let i = 0; i < cats1.length; i++) {
                if(i === cats1.length - 1) {
                info1 += 'and ' + cats1[i] + '.';
                } else {
                info1 += cats1[i] + ', ';
                }
            }
            paragr.textContent = info1;
        </script>
      

JavaScript.info - examples

top
examples
document.getElementById or just id:
              <div id="elem">
                <div id="elem-content">Element</div>
              </div>
              
              <script>
                // get the element
                let elem = document.getElementById('elem');
                // make its background red
                elem.style.background = 'red';
              </script>

              <div id="elem">
                <div id="elem-content">Element</div>
              </div>
              <script>
                // elem is a reference to DOM-element with id="elem"
                elem.style.background = 'red';
                // id="elem-content" has a hyphen inside, so it can't be a variable name
                // ...but we can access it using square brackets: window['elem-content']
              </script>

          
querySlectorAll:
            <ul>
              <li>The</li>
              <li>test</li>
            </ul>
            <ul>
              <li>has</li>
              <li>passed</li>
            </ul>
            <script>
              let elements = document.querySelectorAll('ul > li:last-child');
              for (let elem of elements) {
                alert(elem.innerHTML); // "test", "passed"
              }
            </script>
        
matches:
            <a href="http://example.com/file.zip">...</a>
            <a href="http://ya.ru">...</a>
            
            <script>
              // can be any collection instead of document.body.children
              for (let elem of document.body.children) {
                if (elem.matches('a[href$="zip"]')) {
                  alert("The archive reference: " + elem.href );
                }
              }
          </script>
        
closest:
            <h1>Contents</h1>

            <div class="contents">
              <ul class="book">
                <li class="chapter">Chapter 1</li>
                <li class="chapter">Chapter 2</li>
              </ul>
            </div>
            
            <script>
              let chapter = document.querySelector('.chapter'); // LI
            
              alert(chapter.closest('.book')); // UL
              alert(chapter.closest('.contents')); // DIV
            
              alert(chapter.closest('h1')); // null (because h1 is not an ancestor)
            </script>
        
getElementsBy*:
            // get all divs in the document
            let divs = document.getElementsByTagName('div');

            <table id="table">
              <tr>
                <td>Your age:</td>
                <td>
                  <label>
                    <input type="radio" name="age" value="young" checked> less than 18
                  </label>
                  <label>
                    <input type="radio" name="age" value="mature"> from 18 to 50
                  </label>
                  <label>
                    <input type="radio" name="age" value="senior"> more than 60
                  </label>
                </td>
              </tr>
            </table>
            
            <script>
              let inputs = table.getElementsByTagName('input');
              for (let input of inputs) {
                alert( input.value + ': ' + input.checked );
              }
            </script>